package com.gnerv.sylvanas.framework.core.exception;

import com.fasterxml.jackson.core.type.TypeReference;
import com.gnerv.sylvanas.framework.common.model.RestResult;
import com.gnerv.sylvanas.framework.common.model.RestResultCode;
import com.gnerv.sylvanas.framework.core.tools.JsonTools;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author Gnerv LiGen
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {




    @ResponseBody
    @ExceptionHandler(value = ParameterException.class)
    public RestResult<Void> handlerParameterException(HttpServletRequest req, Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        return JsonTools.fromJsonString(e.getMessage(), new TypeReference<RestResult<Void>>() {});
    }


    @ResponseBody
    @ExceptionHandler(value = BaseException.class)
    public RestResult<Void> handlerBaseException(HttpServletRequest req, BaseException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        return JsonTools.fromJsonString(e.getMessage(), new TypeReference<RestResult<Void>>() {});
    }


    /**
     * 通用异常处理
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public RestResult<Void> defaultErrorHandler(HttpServletRequest req, Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        return RestResult.error(RestResultCode.CODE_500);
    }

}

